package com.ntschy.framework.service;

import cn.hutool.core.util.ObjectUtil;
import com.ntschy.common.core.entity.dataobject.SysUser;
import com.ntschy.common.core.entity.enums.SysWhetherEnum;
import com.ntschy.common.core.model.LoginUser;
import com.ntschy.common.exception.CustomException;
import com.ntschy.common.exception.UserPasswordNotMatchException;
import com.ntschy.sys.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ezreal_geng
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.fetchUserDetailByUserName(username);

        if (ObjectUtil.isNull(user)) {
            log.info("无此帐号：{}", username);
            throw new UserPasswordNotMatchException();
        } else if (SysWhetherEnum.IS == user.getIsDisabled()) {
            log.info("帐号：{} 已被冻结", username);
            throw new CustomException("账号：" + username + " 已禁用");
        }
        // 设置缓存用户信息
        return createLoginUser(user);
    }


    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
